const express = require('express');
const router = express.Router();
const moment = require('moment');
const AccountModel = require('../../db/modules/AccountModule');
let checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware');


/* 记账本列表 */
router.get('/account', checkTokenMiddleware, function(req, res, next) {
    console.log(req.user);
    AccountModel.find().sort({time: -1}).then((data)=>{
      console.log('读取成功');
      res.json({
          code:"0000",
          msg:"读取成功",
          data:data
      })
      // res.render('list',{accounts:data,moment});
      return true;
    }).catch(err=>{
      res.json({
          code:"1002",
          msg:"获取失败~",
          data:null
      })
      return;
    })
});
//添加记录
router.get('/account/create',checkTokenMiddleware,function(req,res,next){
  res.render('create');
})
router.post('/account',checkTokenMiddleware,(req,res)=>{
  AccountModel.create({
    ...req.body,
    time:moment(req.body.time).toDate()
  }).then((data)=>{
    console.log("添加成功");
    res.json({
        code:"0000",
        msg:"创建成功",
        data:data
    })
    return true;
  }).catch((err)=>{
    res.json({
        code:"1002",
        msg:"创建失败~",
        data:null
    })
    return false;
  })
})
router.delete('/account/:id',checkTokenMiddleware,(req,res)=>{
  let id = req.params.id;
  //获取 params 的id参数
  AccountModel.deleteOne({_id:id}).then((data)=>{
    res.json({
        code:"0000",
        msg:"删除成功",
        data:data
    })
  }).catch((err)=>{
    res.json({
        code:"1003",
        msg:"删除失败",
        data:null
    })
    return;
  })
})
router.get('/account/:id',checkTokenMiddleware,(req,res)=>{
    let {id} = req.params;
    AccountModel.findById(id).then((data)=>{
        res.json({
            code:"0000",
            msg:"读取成功",
            data:data
        })
    }).catch((err)=>{
        res.json({
            code:"1004",
            msg:"获取失败~",
            data:null
        })
    })
})
router.patch('/account/:id',checkTokenMiddleware,(req,res)=>{
    let {id} = req.params;
    console.log(req.body);
    AccountModel.updateOne({_id:id}, req.body).then((data)=>{
        AccountModel.findById(id).then((data)=>{
            res.json({
                code:"0000",
                msg:"修改成功",
                data:data
            })
        }).catch((err)=>{
            res.json({
                code:"1004",
                msg:"获取失败~",
                data:null
            })
        })
    }).catch((err)=>{
        res.json({
            code:"1005",
            msg:"更新失败",
            data:null
        })
    })
})
module.exports = router;